package com.firstcare.android_dylibrary.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * 主界面frament的适配器
 * @author chenyichao
 *
 */
public class FramentPagerAdapter extends PagerAdapter {
    FragmentManager framentmanager;
    List<Fragment> list;
    public FramentPagerAdapter(FragmentManager fragmentManager,
                               List<Fragment> li) {
        this.framentmanager = fragmentManager;
        this.list = li;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment frament = list.get(position);
        if (!frament.isAdded()) {
            android.support.v4.app.FragmentTransaction ft = framentmanager
                    .beginTransaction();
            ft.add(frament, frament.getClass().getSimpleName());
            ft.commitAllowingStateLoss();
            framentmanager.executePendingTransactions();
        }
        if (frament.getView().getParent() == null) {
            container.addView(frament.getView());
        }
        return frament.getView();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(list.get(position).getView());
    }

}
